<template>
  <pageSolt @goBack="goBack">
    <template slot="title">{{ taskDetail.name }}</template>
    <template slot="oprate">
      <el-button-group style="margin-right: 10px">
        <el-button
           v-if="['notTurnedOn', 'paused'].indexOf(taskDetail.status) > -1 && typeProp !== 'my'"
           v-functions='["auto_call_task_list_start_pause"]'
          @click="changeState(taskDetail, 'turnedOn')"
          size="mini"
          >开启</el-button
        >
        <el-button
          v-if="['dealing'].indexOf(taskDetail.status) > -1 && typeProp !== 'my'"
          v-functions='["auto_call_task_list_start_pause"]'
          @click="changeState(taskDetail, 'paused')"
          size="mini"
          >暂停</el-button
        >
        <el-button
          v-if="['notTurnedOn', 'paused', 'complete'].indexOf(taskDetail.status) > -1 && typeProp !== 'my'"
          v-functions='["auto_call_task_list_edit"]'
          @click="handleEdit"
          size="mini"
          >编辑</el-button
        >
        <el-button
          @click="changeState(taskDetail, 'archived')"
          v-if="['notTurnedOn', 'paused', 'complete'].indexOf(taskDetail.status) > -1 && typeProp !== 'my'"
          v-functions='["auto_call_task_list_archive"]'
          size="mini"
          >归档</el-button
        >
        <el-button
          v-if="['notTurnedOn', 'paused', 'complete'].indexOf(taskDetail.status) > -1 && typeProp !== 'my'"
          v-functions='["auto_call_task_list_delete"]'
          @click="handleDeleteById(taskDetail)"
          size="mini"
          >删除</el-button
        >
      </el-button-group>
      <el-dropdown @command="handleCommand" v-show="taskDetail.status !== 'archived'">
        <el-button type="primary" size="mini" v-if="typeProp === 'my'" v-functions="['my_auto_call_task_list_import']">
          导入号码<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-button type="primary" size="mini" v-else v-functions="['auto_call_task_list_import']">
          导入号码<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            command="single"
            >单个导入</el-dropdown-item
          >
          <el-dropdown-item
            command="multiple"
            >批量导入</el-dropdown-item
          >
          <el-dropdown-item
            command="history"
            >查看导入历史</el-dropdown-item
          >
        </el-dropdown-menu>
      </el-dropdown>

      <el-dialog
        title="单个导入"
        :modal-append-to-body="false"
        :visible.sync="dialogFormVisible"
        @close="singDialogClose"
        :width="'30%'"
      >
        <el-form
          :model="singleForm"
          :rules="singleFormRules"
          ref="singleForm"
          label-width="0"
          class="demo-ruleForm"
        >
          <el-form-item prop="phoneList">
            <el-input
              type="textarea"
              :rows="10"
              placeholder="请输入内容"
              v-model="singleForm.phoneList"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="singleExport('singleForm')"
            >确认导入</el-button
          >
        </div>
      </el-dialog>
      <el-dialog
        title="批量导入"
        :visible.sync="batchImportVisible"
        @close="batchDialogClose"
        :modal-append-to-body="false"
        :width="'40%'"
      >
        <div class="batch-import-row">
          <div class="batch-import-row-tit">
            导入号码<span class="tip"></span>
          </div>
          <div class="batch-import-row-oprate">
            <el-upload
              class="upload-demo"
              ref="batchUpload"
              :action="batchUrl"
              :on-success="handleSuccess"
              :before-upload="beforeAvatarUpload"
              :limit="1"
              :headers="{
                sessionid: userId,
                loginToken: loginToken
              }"
            >
              <el-button size="small" slot="trigger" class="button"
                >点击上传</el-button
              >
              <el-button size="small" class="button"
                ><a
                  href="/temp/auto-call-template.xlsx"
                  download="自动外呼号码模板"
                  >下载导入号码模板</a
                ></el-button
              >
            </el-upload>
          </div>
        </div>
        <div class="batch-import-row">
          <div class="batch-import-row-tit">
            查重规则<span class="tip"></span>
          </div>
          <div class="batch-import-row-oprate">
            <el-radio v-model="batchForm.callTaskRepeatRule" label="2"
              >所有任务<span class="tip">（所有未归档的任务）</span></el-radio
            >
            <el-radio v-model="batchForm.callTaskRepeatRule" label="1"
              >当前任务<span class="tip">（当前操作的任务）</span></el-radio
            >
            <el-radio v-model="batchForm.callTaskRepeatRule" label="3"
              >不查重</el-radio
            >
          </div>
        </div>
        <div class="batch-import-row">
          <div class="batch-import-row-tit">备注<span class="tip"></span></div>
          <div class="batch-import-row-oprate">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入任务备注"
              v-model="batchForm.comment"
            >
            </el-input>
          </div>
        </div>
        <div class="batch-import-row">
          <div class="batch-import-row-tit">
            温馨提示<span class="tip"></span>
          </div>
          <div class="batch-import-row-oprate column">
            <p>1、支持后缀为xls和xlsx的excel文件导入；</p>
            <p>2、导入号码的表头不能修改；</p>
            <p>3、单次批量导入客户数据上限10000条；</p>
            <p>
              4、号码格式支持手机和电话，电话需包含区号，号码为空的数据不会导入；
            </p>
            <p>
              5、导入是异步处理的,提交导入后可以立刻进行其他的导入,服务器会排队处理
            </p>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="batchExport">确认导入</el-button>
        </div>
      </el-dialog>
    </template>
    <template slot="content">
      <div class="details-content" ref="dataContent">
        <div class="data-details" ref="dataDetails">
          <!-- <div class="data-details-title">任务详情</div> -->
          <div class="data-details-con">
            <div class="data-details-data" :class="typeProp === 'my'?'dash-border':''" v-show="isShowDetails">
              <el-row class="list">
                <el-col :span="6">
                  <span class="list-tit">任务名称:</span>
                  <span class="ellipsis-box">{{ taskDetail.name }}</span>
                </el-col>
                <el-col :span="6">
                  <span class="list-tit">任务类型:</span>
                  <span>自动外呼</span></el-col>
                <el-col :span="6">
                  <span class="list-tit">任务状态:</span>
                  <span>{{ taskDetail | getTaskStatus }}</span>
                </el-col>
                <el-col :span="6">
                  <span class="list-tit">创建时间:</span>
                  <span>{{ taskDetail.createTime }}</span>
                </el-col>
              </el-row>
              <el-row class="list">
                <el-col :span="6">
                  <span class="list-tit">创建人:</span>
                  <span class="ellipsis-box">{{ taskDetail.createUserName }}</span>
                </el-col>
                <el-col :span="6">
                  <span class="list-tit">最大并发:</span>
                  <span v-if="taskDetail.callStrategy">{{taskDetail.callStrategy.concurrentType === 'stable' ?  taskDetail.callStrategy.concurrent : taskDetail.callStrategy.maxConcurrent}}</span>
                </el-col>
                <el-col :span="6">
                  <span class="list-tit">语音导航:</span>
                  <span class="ellipsis-box">{{ taskDetail.ivrName }}</span>
                </el-col>
              </el-row>
              <el-row
                class="list"
                v-show="taskDetail.description && taskDetail.description.length > 0"
              >
                <el-col :span="24">
                  <span class="list-tit">任务描述:</span>
                  <span>{{ taskDetail.description }}</span>
                </el-col>
              </el-row>
            </div>
            <outboundOprate
              :data="taskDetail"
              v-if="typeProp === 'my'"
              @showDetail="showDetail"
              @dialoutSuccess="dialoutSuccess"
            ></outboundOprate>
          </div>
        </div>
        <div class="data-list" :style="{ height: dataListHeight + 'px' }">
          <el-tabs v-model="activeName" ref="eltabs">
            <el-tab-pane label="执行情况" name="executeList" v-if="typeProp=== 'admin'"></el-tab-pane>
            <el-tab-pane label="数据列表" name="dataList"></el-tab-pane>
            <el-tab-pane label="通话记录" name="callDataList"></el-tab-pane>
          </el-tabs>
          <component
            :style="{ height: commonHeight + 'px' }"
            :data="data"
            :is="activeName"
            :ref="activeName"
            :forceCondition="dataCenterCondition"
            :isCustom="true"
            :moduleType="moduleType"
            :visibleDialout="false"
            :typeProp="typeProp"
          >
            <template slot="search">
              <QuickSearch
                :advForm="callDataSearchForm"
              ></QuickSearch>
            </template>
            <template slot="oprate">
              <el-button type="primary" @click="refreshCallData" size="mini">刷新</el-button>
            </template>
          </component>
        </div>
      </div>
    </template>
  </pageSolt>
</template>

<script lang="ts">
import { Component, Prop, Mixins, Watch } from 'vue-property-decorator'
import pageSolt from '../../../components/callTaskCommon/pageSolt.vue'
import taskMixin from '../../../components/callTaskCommon/task-mixin'
import { IvrModule } from '@/store/modules/config/ivr'

import executeList from './executeList.vue'
import dataList from './dataList.vue'
import callDataList from '@/views/dataCenter/callData/index.vue'
import outboundOprate from '../../../components/callTaskCommon/outboundOprate.vue'
import { deepClone } from '@/utils/common'

import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import cloneDeep from 'lodash/cloneDeep'

const phonevalidate = (rule, value, callback) => {
  const phoneList = value.split(/[\r\n]/)
  const regNum = new RegExp('^[0-9]*$')
  const regSpace = new RegExp(/\s/)
  let flag = true
  phoneList.some((phone) => {
    if (!regNum.test(phone) || regSpace.test(phone)) {
      flag = false
      return true
    }
  })
  if (!flag) {
    callback(new Error('请输入正确号码'))
  } else {
    callback()
  }
}
@Component({
  name: 'autoCallDetails',
  components: { pageSolt, executeList, dataList, callDataList, outboundOprate, QuickSearch }
})
export default class PriviewDetails extends Mixins(taskMixin) {
  @Prop({ default: {} }) private data: any
  @Prop({ default: 'my' }) private typeProp: any
  @Prop({ default: '' }) private moduleType: any
  private activeName = 'executeList'
  private taskDetail: any = {}
  private dialogFormVisible = false
  private batchImportVisible = false

  private $confirm: any

  private isShowDetails = false

  private batchImportPath: string = ''
  private singleForm = {
    phoneList: ''
  }

  private singleFormRules = {
    phoneList: [
      { required: true, message: '请输入导入号码', trigger: 'blur' },
      { validator: phonevalidate, trigger: 'blur', message: '请输入正确号码，用回车分割' }
    ]
  }

  private batchForm = {
    callTaskRepeatRule: '2',
    comment: ''
  }

  private dataListHeight = 0
  private commonHeight = 0
  private $router: any

  get batchUrl () {
    return '/upload?accountId=' + this.account + '&module=call'
  }

  get dataCenterCondition () {
    const condition: any[] = [
      {
        fieldKey: 'callType',
        fieldOperator: 'eq',
        fieldValue: [
          'autoDialout'
        ]
      },
      {
        fieldKey: 'taskId',
        fieldOperator: 'eq',
        fieldValue: [
          this.taskDetail._id
        ]
      },
      {
        fieldKey: 'agentName',
        fieldOperator: 'in',
        fieldValue: [
          this.callDataSearchForm.form.customerOrAgentName
        ]
      }
    ]
    if (this.callDataSearchForm.form.time && this.callDataSearchForm.form.time.length > 1) {
      condition.push({
        fieldKey: 'startTime',
        fieldOperator: 'between',
        fieldValue: this.callDataSearchForm.form.time
      })
    }
    return {
      advanceQuery: [
        condition
      ]
    }
  }

  private callDataSearchForm = { // 快捷检索数据
    form: {
      customerOrAgentName: '',
      time: []
    },
    advSearchOptions: [ // 快捷检索的数据
      { label: '名称', inputType: 'input', placeholder: '输入名称', name: 'customerOrAgentName', clearable: true },
      { label: '呼叫时间', inputType: 'dateTimeRange', clearable: true, name: 'time' }
    ]
  }

  private phoneList: string = ''
  private showDetail (isShowDetail: boolean) {
    this.isShowDetails = isShowDetail
    this.$nextTick(() => {
      this.setDataListHeight();
      (this.$refs as any)[this.activeName].handleSetTabelHeight()
    })
  }

  private dialoutSuccess () {
    this.$emit('screen');
  }

  private goBack () {
    this.$emit('back')
  }

  private handleDeleteById (row: any) {
    (this.$confirm as any)('确定删除该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const taskId = row._id
      this.handleDelete(taskId).then((success) => {
        if (success) {
          this.$emit('back', true)
        }
      })
    }).catch(e => {
      console.log(e)
    })
  }

  private changeState (row: any, status: string) {
    const taskId = row._id
    const oldStatus = row.status
    row.status = status
    this.updateTaskState(taskId, status).then((res: any) => {
      if (res && res.data) {
        row.status = res.data.status
      } else {
        row.status = oldStatus
      }
    })
  }

  private handleEdit () {
    this.$emit('edit')
  }

  private handleCommand (command: string) {
    if (command === 'single') {
      this.dialogFormVisible = true
    } else if (command === 'multiple') {
      this.batchImportPath = ''
      this.batchImportVisible = true
    } else if (command === 'history') {
      this.jumpToTransmissionCenter()
    }
  }

  private singleExport (formName: string) {
    (this.$refs as any)[formName].validate((valid) => {
      if (valid) {
        const actionData = Object.assign({ phone: this.singleForm.phoneList, taskId: this.taskDetail._id })
        const data = { url: '/call/action/autoCallTask/import', method: 'POST', data: actionData }
        IvrModule.IvrCommonAction(data).then((res: any) => {
          if (res.success) {
            (this.$message as any)({ message: '导入成功', type: 'success' });
            this.dialogFormVisible = false
            this.singDialogClose()
            if (this.activeName === 'dataList') { // 导入成功之后，如果当前tab是数据列表，刷新
              (this as any).$refs.dataList.fetchData()
            }
            this.getTaskInfo()
          }
        })
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }

  private getTaskInfo () {
    const data = { url: `/call/action/autoCallTask/${this.taskDetail._id}`, method: 'GET', hideLoading: true, data: {} }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res && res.success && res.data) {
        const agentObj = deepClone(this.$store.state.common.publicCache.userListObj)[res.data.createUser]
        const ivrObj = deepClone(this.$store.state.common.publicCache.ivrListObj)[res.data.ivrId]
        this.taskDetail = res.data
        this.taskDetail.createUserName = agentObj ? agentObj.name : '--'
        this.taskDetail.ivrName = ivrObj ? ivrObj.name : '--'
      }
    })
  }

  private jumpToTransmissionCenter () { // 跳转到传输中心
    this.$router.push(`/transmission_center/index/tx_import_task?taskModule=autoCallTask&previewTaskId=${this.data._id}`)
  }

  private batchExport () {
    if (!this.batchImportPath) {
      (this.$message as any)({ message: '请导入号码文件', type: 'error' });
      return
    }
    const actionData = {
      type: 'autoCallTask',
      filepath: this.batchImportPath,
      extra: {
        autoCallTaskId: this.taskDetail._id,
        autoCallTaskRepeatRule: this.batchForm.callTaskRepeatRule
      },
      createUser: this.userId,
      comment: this.batchForm.comment
    }
    const data = { url: '/base/action/transmission/import/task/create', method: 'POST', data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res.success) {
        const h = this.$createElement;
        (this.$message as any)({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, '导入成功，请前往'),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
        this.batchImportVisible = false
        this.batchImportPath = ''
      }
      setTimeout(() => { // setTimeout，导入任务是异步的
        this.getTaskInfo()
      }, 500)
    })
  }

  private handleSuccess (res) {
    const success = res.success
    const data = res.data || {}
    if (success) {
      this.batchImportPath = data.path
    }
  }

  private setTaskDetail (data: any) { // 由父级调用（在详情中修改任务信息）
    this.taskDetail = data
  }

  private mounted () {
    this.taskDetail = cloneDeep(this.data)
    this.setDataListHeight()
    this.isShowDetails = this.typeProp === 'admin' || false
    this.activeName = this.typeProp === 'admin' ? 'executeList' : 'dataList'
  }

  private setDataListHeight () {
    const dataContentH = (window as any).getComputedStyle((this.$refs as any).dataContent).height
    const detaildH = (window as any).getComputedStyle((this.$refs as any).dataDetails).height
    const eltabsH = (window as any).getComputedStyle((this.$refs as any).eltabs.$el).height
    const dataListHeight = parseInt(dataContentH, 10) - parseInt(detaildH, 0)
    this.dataListHeight = dataListHeight
    this.commonHeight = this.typeProp === 'my' ? dataListHeight - 68 : dataListHeight - 138
  }

  private singDialogClose () {
    this.singleForm.phoneList = ''
  }

  private batchDialogClose () {
    (this.$refs as any).batchUpload.clearFiles();
    this.batchImportPath = ''
    this.batchForm = {
      callTaskRepeatRule: '2',
      comment: ''
    }
  }

  private refreshCallData () {
    if (this.activeName === 'callDataList') {
      (this.$refs as any)[this.activeName].pageChange(1)
    }
  }

  private beforeAvatarUpload (file) {
    const fileTypeList = [
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'xlsx',
      'xls'
    ]
    const isExcel = fileTypeList.some((type) => {
      return type === file.type || file.type.indexOf(type) !== -1
    })
    if (!isExcel) {
      (this.$message as any).error('请上传.xls或者.xlsx文件')
      return false
    }
    return true
  }

  @Watch('data')
  private dataChange (current) {
    this.taskDetail = current
  }
}
</script>

<style lang="stylus">
.el-button.is-round
  padding 6px 14px
</style>

<style lang="stylus" scoped>
.batch-import-row
  display flex
  flex-direction column
  margin-bottom 10px
  .tip
    color #B3B9C7
  .batch-import-row-tit
    font-size 12px
    color #303753
    margin-bottom 10px
  .batch-import-row-oprate
    display flex
    .button
      margin-right 10px
      padding 10px 63px 10px
  .column
    flex-direction column
    p
      font-size 12px
      color #767E91
      font-weight normal
.data-details-title
  font-size 14px
  margin-bottom 15px
  font-weight 600
.details-content
  height 100%
  padding 16px
  box-sizing border-box
.data-details-con
  background #F4F9FD
  padding 0 24px 0
  border-radius 4px
  .data-details-data
    // display flex
    padding 5px 0 5px
    flex-wrap wrap
    overflow hidden
    .list
      margin 11px 0 11px
      color #767E91
    .list-tit
      font-weight 600
      color #303753
      margin-right 8px
  .dash-border
    border-bottom 1px dashed #e7e9ed
.data-details-oprate
  // display flex
  justify-content space-between
  align-items center
  padding 16px 0px 16px
  box-sizing border-box
  .data-details-oprate-row
    display flex
    align-items center
    .oprate-tit
      color #767E91
      margin-right 8px
    .oprate-con
      color #008BEE
      font-size 16px
      font-weight 600
    .oprate-btn
      width 20%
      display flex
      justify-content flex-end
      .V7_iconfont
        font-size 12px
.ellipsis-box
    max-width 11em
    text-overflow ellipsis
    overflow hidden
    white-space nowrap
    display inline-block
    vertical-align bottom
</style>
